package com.jiangyg.mall.core.support.validation.constraints;

import com.jiangyg.mall.core.support.validation.AbstractConstraintValidator;
import org.apache.commons.lang.StringUtils;
import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.regex.Pattern;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * 类描述：手机号码校验
 * 
 * @author jiangyg
 * @date 2020-08-02
 * @version 2.0
 */
@Documented
@Retention(RUNTIME)
@Constraint(validatedBy = { Phone.PhoneConstraintValidator.class })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
public @interface Phone {

    String message() default "{custom.validation.constraints.Phone.message}";

    String regexp() default "^([1]\\d{10}|([\\(（]?0[0-9]{2,3}[）\\)]?[-]?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?)$";

    /**
     * 分组，用于判断在那种情况下执行校验
     */
    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * 类描述：手机号码校验执行器
     * 
     * @author jiangyg
     * @date 2020-08-02
     * @version 2.0
     */
    class PhoneConstraintValidator extends AbstractConstraintValidator<Phone, String> {

        @Override
        public boolean execute(Phone a, String value, ConstraintValidatorContextImpl contextImpl) {
            if (StringUtils.isBlank(value)) {
                return true;
            }
            return Pattern.matches(a.regexp(), value);
        }

    }

}
